/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.ui.template;

import com.bytedance.scene.Scene;
import com.bytedance.scene.group.GroupScene;
import com.bytedance.scene.ui.ResourceTable;
import com.bytedance.scene.ui.view.ext.SlideMenu;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by JiangQi on 8/24/18.
 */
public abstract class NavigationViewScene extends GroupScene {
    private SlideMenu slideMenu;
    private StackLayout slMenuSwitch;
    private Image imageMenuSwitch;
    private Text textTitle;
    private ListContainer lcMenuList;
    private List<String> listMenuData;

    private Component menuContent;

    @Override
    public ComponentContainer onCreateView(LayoutScatter inflater, ComponentContainer container, Intent savedInstanceState) {
        ComponentContainer componentContainer = null;
        if (getType() == 0) {
            componentContainer = (ComponentContainer) inflater.parse(ResourceTable.Layout_scene_navigation_view_layout, container, false);
            menuContent = (LayoutScatter.getInstance(requireSceneContext()).parse(ResourceTable.Layout_slide_menu, null,false));
        } else if (getType() == 1) {
            componentContainer = (ComponentContainer) inflater.parse(ResourceTable.Layout_scene_navigation_view_layout_two, container, false);
            menuContent = (LayoutScatter.getInstance(requireSceneContext()).parse(ResourceTable.Layout_slide_menu_2, null,false));
        }
        return componentContainer;
    }

    @Override
    public void onViewCreated(Component component, Intent intent) {
        super.onViewCreated(component, intent);

    }

    @Override
    public void onActivityCreated(Intent intent) {
        super.onActivityCreated(intent);
        slideMenu = findViewById(ResourceTable.Id_swipeRevealLayout);
        slMenuSwitch = findViewById(ResourceTable.Id_sl_titleBar_menu_switch);
        imageMenuSwitch = findViewById(ResourceTable.Id_image_titleBar_menu_switch);
        textTitle = findViewById(ResourceTable.Id_text_titleBar_title);

        Component sl_navigation_view_content = findViewById(ResourceTable.Id_sl_navigation_view_content);

        slideMenu.setIgnoreComponents(sl_navigation_view_content);
        slideMenu.setIgnoreComponents(slMenuSwitch);
        slideMenu.initMenu(menuContent);


        lcMenuList = findViewById(ResourceTable.Id_lc_navigation_menu);

        //打开侧边菜单
        slMenuSwitch.setClickedListener(component -> {
            slideMenu.open();
        });
        slideMenu.setSlideMenuStateListener(new SlideMenu.SlideMenuStateListener() {
            @Override
            public void onSlideMenuOpened() {
                AnimatorProperty animatorProperty=new AnimatorProperty();
                animatorProperty.setTarget(imageMenuSwitch)
                        .rotate(-45).setDuration(100).start();
            }

            @Override
            public void onSlideMenuClosed() {
                AnimatorProperty animatorProperty=new AnimatorProperty();
                animatorProperty.setTarget(imageMenuSwitch)
                        .rotate(0).setDuration(100).start();
            }
        });

        listMenuData = new ArrayList<>(getSceneMap().keySet());
        if(getType()==0){
            MyMenuProvider baseItemProvider = new MyMenuProvider(getSceneContext(), listMenuData);
            lcMenuList.setItemProvider(baseItemProvider);
            lcMenuList.setItemClickedListener((listContainer, component, position, l) -> {
                baseItemProvider.setSelectedPosition(position);
                setTitle(listMenuData.get(position));
                //关闭侧边栏
                slideMenu.close();
                String tag = (String) listContainer.getItemProvider().getItem(position);
                updateContent(tag);

            });
            //关闭侧边栏
            //swipeRevealLayout.open(false);

            lastSelectTag = listMenuData.get(0);
            //设置第一个界面
            updateContent(listMenuData.get(0));
            setTitle(listMenuData.get(0));
        }else{
            MyMenuProvider_two baseItemProvider = new MyMenuProvider_two(getSceneContext(), listMenuData);
            lcMenuList.setItemProvider(baseItemProvider);
            lcMenuList.setItemClickedListener((listContainer, component, position, l) -> {
                baseItemProvider.setSelectedPosition(position);
                setTitle(listMenuData.get(position));
                //关闭侧边栏
               slideMenu.close();
                String tag = (String) listContainer.getItemProvider().getItem(position);
                updateContent(tag);

            });
            //关闭侧边栏
            //swipeRevealLayout.open(false);

            lastSelectTag = listMenuData.get(0);
            //设置第一个界面
            updateContent(listMenuData.get(0));
            setTitle(listMenuData.get(0));
        }


    }

    /**
     * 上一个的选中的Tag
     **/
    private String lastSelectTag = "";

    private void updateContent(String tag) {
        Scene scene = findSceneByTag(tag);
        if (scene == null) {
            scene = getSceneMap().get(tag);
        }

        //没有-添加，有-显示
        if (!isAdded(scene)) {
            add(ResourceTable.Id_sl_navigation_view_content, scene, tag);
        } else if (!isShow(scene)) {
            show(scene);
        }

        //隐藏旧的页面
        if (!lastSelectTag.equals(tag)) {
            Scene lastScene = findSceneByTag(lastSelectTag);
            hide(lastScene);
            lastSelectTag = tag;
        }
    }


    protected abstract LinkedHashMap<String, Scene> getSceneMap();


    public void setTitle(CharSequence title) {
        textTitle.setText(title.toString());
    }

    public void setTitle(int titleId) {
        setTitle(getText(titleId));
    }


    private class MyMenuProvider extends BaseItemProvider {
        private int selectedPosition = 0;

        public void setSelectedPosition(int selectedPosition) {
            this.selectedPosition = selectedPosition;
            notifyDataChanged();
        }

        private final Context mContext;
        private final List<String> listData;

        public MyMenuProvider(Context mContext, List<String> listData) {
            this.mContext = mContext;
            this.listData = listData;
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int i) {
            return listData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            final Component cpt;
            ComponentHolder holder;
            String data = listData.get(position);
            if (component == null) {
                cpt = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_item_navigation_menu, componentContainer, false);
                holder = new ComponentHolder(cpt);
                cpt.setTag(holder);
            } else {
                cpt = component;
                holder = (ComponentHolder) cpt.getTag();
            }

            holder.textContent.setText(data);

            if (position == selectedPosition) {
                holder.textContent.setTextColor(new Color(Color.getIntColor("#3F51B5")));
            } else {
                holder.textContent.setTextColor(new Color(Color.getIntColor("#202020")));
            }

            return cpt;
        }

        public class ComponentHolder {
            Text textContent;

            public ComponentHolder(Component component) {
                textContent = (Text) component.findComponentById(ResourceTable.Id_text_item_navigation_menu_content);
            }
        }

    }


}
